package secondriver.process.core;

import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 增强的Properties
 * <p>
 * 0.可以在value中使用引用环境变量,系统属性，如 ${JAVA_HOME},${user.home}
 * <p>
 * 1.环境变量,系统属性的名称的有效字符有字母，数字，下划线，连接符，点
 * <p>
 * 2.引用值的读取覆盖顺序为：环境变量，系统属性
 * <p>
 * 例子：
 * <pre>
 * port:1234
 * staticFileLocation:${user.home}
 * </pre>
 * <p>
 * Author : secondriver
 * Date :  2016/1/4
 */
public class EnhanceProperties extends Properties {

    private static final Pattern KEY_PLACEHOLDER_PATTERN = Pattern.compile("\\$\\{[0-9a-zA-Z-_\\.]+\\}");

    public EnhanceProperties() {
    }

    public EnhanceProperties(Properties defaults) {
        super(defaults);
    }

    @Override
    public String getProperty(String key) {
        Object oval = super.get(key);
        String sval = (oval instanceof String) ? (String) oval : null;
        String use = sval;
        if (use != null) {
            Matcher m = KEY_PLACEHOLDER_PATTERN.matcher(use);
            while (m.find()) {
                String v = m.group();
                String k = v.substring("${".length(), v.length() - "}".length());
                String rv = System.getenv(k);
                if (rv == null) {
                    rv = System.getProperty(k);
                }
                if (rv != null) {
                    sval = sval.replace(v, rv);
                }
            }
        } else {
            sval = System.getenv(key);
            if (sval == null) {
                sval = System.getProperty(key);
            }
        }
        return ((sval == null) && (defaults != null)) ? defaults.getProperty(key) : sval;
    }

    @Override
    public String getProperty(String key, String defaultValue) {
        String val = getProperty(key);
        return (val == null) ? defaultValue : val;
    }
}